package com.hyx.api.utils.base;

import com.hyx.api.domain.User;
import com.hyx.api.utils.ApiTokenUtils;
import com.ruoyi.common.exception.ServiceException;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

public class MobileBaseService {

    /*验证是否登录*/
    public User hasLogin() {
        User user = ApiTokenUtils.getLoginUser(getHttpServletRequest());
        if(ObjectUtils.isEmpty(user))
            needLogin();
        return user;
    }

    public Long getLoginUserId() {
        User user = ApiTokenUtils.getLoginUser(getHttpServletRequest());
        if(ObjectUtils.isEmpty(user))
            return 0L;
        return user.getId();
    }

    public void needLogin() {
        throw new ServiceException("请登录",401);
    }

    public void logout() {
        ApiTokenUtils.delLoginUser(getHttpServletRequest());
    }

    /**
     * 获取HttpServletRequest
     * @return
     */
    protected HttpServletRequest getHttpServletRequest() {
        return getServletRequestAttributes().getRequest();
    }

    protected ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes());
    }
}
